package com.example.tools.httputils.ok;

import android.util.Log;

import com.example.tools.httputils.callback.OnUpdateFileCallBack;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;
import okio.BufferedSink;
import okio.Okio;
import okio.Source;

/**
 * Created by Administrator on 2016/10/19.
 */

public class UpDateBuilder {

    private static UpDateBuilder updatebuilder =new UpDateBuilder();

    private static final MediaType MEDIA_OBJECT_STREAM = MediaType.parse("application/octet-stream");//mdiatype 这个需要和服务端保持一致

    private UpDateBuilder() {}

    public static UpDateBuilder getInstens(){
       return updatebuilder;
    }

    public <T> void update(OkHttpClient okHttpClient,String actionUrl, HashMap<String, Object> paramsMap, final OnUpdateFileCallBack callBack){
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        for (String key : paramsMap.keySet()) {
            Object object = paramsMap.get(key);
            if (!(object instanceof File)) {
                builder.addFormDataPart(key, object.toString());
            } else {
                File file = (File) object;
                builder.addFormDataPart(key, file.getName(), createProgressRequestBody(MEDIA_OBJECT_STREAM, file, callBack));
            }
        }
        //创建RequestBody
        RequestBody body = builder.build();
        //创建Request
        final Request request = new Request.Builder().url(actionUrl).post(body).build();
        final Call call = okHttpClient.newBuilder().writeTimeout(50, TimeUnit.SECONDS).build().newCall(request);
        call.enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                callBack.message("上传失败！");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    callBack.message("上传成功！");
                    String string = response.body().string();
                    Log.e("TAG", "response ----->" + string);
                } else {
                    callBack.message("上传失败！");
                }
            }
        });
    }

    public RequestBody createProgressRequestBody(final MediaType contentType, final File file, final OnUpdateFileCallBack callBack) {

        return new RequestBody() {
            @Override
            public MediaType contentType() {
                return contentType;
            }

            @Override
            public long contentLength() {
                return file.length();
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                Source source;
                try {
                    source = Okio.source(file);
                    Buffer buf = new Buffer();
                    long remaining = contentLength();
                    long current = 0;
                    for (long readCount; (readCount = source.read(buf, 2048)) != -1; ) {
                        sink.write(buf, readCount);
                        current += readCount;
                        Log.e("TAG", "current------>" + current);
                        callBack.progress(remaining,current);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
    }
}
